package com.aisino.efence.utils;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author fzc
 * @package com.aisino.efence.utils
 * 请求工具类
 * @create 2018-04-09 15:11
 **/
public class RequestUtil {

    private static final Logger LOG = LoggerFactory.getLogger(RequestUtil.class);

    private String mMetyodType;//请求方式，目前只支持get和post
    private String mUrl;//接口
    private Map<String, String> mParamsMap;//键值对类型的参数，只有这一种情况下区分post和get。
    private String mJsonStr;//json类型的参数，post方式
    private Map<String, String> mHeaderMap;//头参数
    private OkHttpClient mOkHttpClient;//OKhttpClient对象
    private Request mOkHttpRequest;//请求对象
    private Request.Builder mRequestBuilder;//请求对象的构建者


    RequestUtil(String methodType, String url, Map<String, String> paramsMap, Map<String, String> headerMap) {
        this(methodType, url, null, null, null, null, null, null, paramsMap, headerMap);
    }

    RequestUtil(String methodType, String url, String jsonStr, Map<String, String> headerMap) {
        this(methodType, url, jsonStr, null, null, null, null, null, null, headerMap);
    }

    private RequestUtil(String methodType, String url, String jsonStr, File file, List<File> fileList, String fileKey, Map<String, File> fileMap, String fileType, Map<String, String> paramsMap, Map<String, String> headerMap) {
        mMetyodType = methodType;
        mUrl = url;
        mJsonStr = jsonStr;
        mParamsMap = paramsMap;
        mHeaderMap = headerMap;
        getInstance();
    }


    /**
     * 创建OKhttpClient实例。
     */
    private void getInstance() {
        mOkHttpClient = new OkHttpClient()
                .newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        mRequestBuilder = new Request.Builder();
        //设置参数
        switch (mMetyodType) {
            case OkhttpUtil.METHOD_GET:
                setGetParams();
                break;
            case OkhttpUtil.METHOD_POST:
                mRequestBuilder.post(getRequestBody());
                break;
            case OkhttpUtil.METHOD_PUT:
                mRequestBuilder.put(getRequestBody());
                break;
            case OkhttpUtil.METHOD_DELETE:
                mRequestBuilder.delete(getRequestBody());
                break;
            default:
                break;
        }
        mRequestBuilder.url(mUrl);
        if (mHeaderMap != null) {
            setHeader();
        }
        //mRequestBuilder.addHeader("Authorization","Bearer "+"token");可以把token添加到这儿
        mOkHttpRequest = mRequestBuilder.build();
    }

    /**
     * 得到body对象
     */
    private RequestBody getRequestBody() {
        /**
         * 首先判断mJsonStr是否为空，由于mJsonStr与mParamsMap不可能同时存在，所以先判断mJsonStr
         */
        if (!StringUtils.isEmpty(mJsonStr)) {
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");//数据类型为json格式，
            return RequestBody.create(JSON, mJsonStr);//json数据，
        }

        /**
         * post,put,delete都需要body，但也都有body等于空的情况，此时也应该有body对象，但body中的内容为空
         */
        FormBody.Builder formBody = new FormBody.Builder();
        if (mParamsMap != null) {
            for (String key : mParamsMap.keySet()) {
                formBody.add(key, mParamsMap.get(key));
            }
        }
        return formBody.build();
    }


    /**
     * get请求，只有键值对参数
     */
    private void setGetParams() {
        if (mParamsMap != null) {
            mUrl = mUrl + "?";
            for (String key : mParamsMap.keySet()) {
                mUrl = mUrl + key + "=" + mParamsMap.get(key) + "&";
            }
            mUrl = mUrl.substring(0, mUrl.length() - 1);
        }
    }

    /**
     * 设置头参数
     */
    private void setHeader() {
        if (mHeaderMap != null) {
            for (String key : mHeaderMap.keySet()) {
                mRequestBuilder.addHeader(key, mHeaderMap.get(key));
            }
        }
    }

    Response execute() {
        try {
            Response response = mOkHttpClient.newCall(mOkHttpRequest).execute();
            LOG.info("调用[okHttpUtil]-[{}]-[{}]-[{}]",mMetyodType,mUrl, JSON.toJSONString(response.body()));
            if (!response.isSuccessful()) {
                return null;
            }
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            LOG.error("调用[okHttpUtil]-[error]-[{}]",e);
            return null;
        }
    }

}
